﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ReadDogv1
{
    /// <summary>
    /// UcLog.xaml 的交互逻辑
    /// </summary>
    public partial class UcLog : UserControl
    {
        public UcLog()
        {
            InitializeComponent();
            DataContext = ViewModel.GetInstance().log;
        }

        private void button_ClearState_Click(object sender, RoutedEventArgs e)
        {
            ViewModel.GetInstance().log.ClearLog();
            ViewModel.GetInstance().log.DebugLog(-1, $"==========================================================================");
            ViewModel.GetInstance().log.DebugLog(-1, $"烧录加密狗操作步骤如下：");
            ViewModel.GetInstance().log.DebugLog(-1, $"1、单击【更新烧录清单】按钮");
            ViewModel.GetInstance().log.DebugLog(-1, $"2、插入烧录母狗");
            ViewModel.GetInstance().log.DebugLog(-1, $"3、在未插入子狗的状态下，单击【开始烧录任务】按钮");
            ViewModel.GetInstance().log.DebugLog(-1, $"4、插入子狗，会自动按照烧录清单顺序烧录，烧录状态见【烧录任务状态】");
            ViewModel.GetInstance().log.DebugLog(-1, $"5、【烧录任务状态】提示 “ 烧录完成 ”，拔出子狗，插入下一个待烧录子狗");
            ViewModel.GetInstance().log.DebugLog(-1, $"==========================================================================");
            ViewModel.GetInstance().log.DebugLog(-1, $"检查加密狗操作步骤如下：");
            ViewModel.GetInstance().log.DebugLog(-1, $"1、单击【更新烧录清单】按钮");
            ViewModel.GetInstance().log.DebugLog(-1, $"2、单击【开始检查任务】");
            ViewModel.GetInstance().log.DebugLog(-1, $"3、插入子狗，会自动读取狗ID和三个激活码");
            ViewModel.GetInstance().log.DebugLog(-1, $"4、对比服务器注册信息，显示对应烧录任务并显示匹配");
            ViewModel.GetInstance().log.DebugLog(-1, $"==========================================================================");
        }
    }

    public class model_Log : INotifyPropertyChanged
    {
        #region MVVM声明 

        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public model_Log()
        {
            State = new IClassTextBoxAppend();
        }

        private object lockObject = new object();
        public void DebugLog(string obj)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                var timeNow = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string strLog = $"[{timeNow}] : {obj}\r\n";
                lock (lockObject)
                {
                    State.Append(strLog, 0);
                }
            });
        }

        public void DebugLog(int insert, string obj)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                var timeNow = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string strLog = $"[{timeNow}] : {obj}\r\n";
                lock (lockObject)
                {
                    State.Append(strLog);
                }
            });
        }

        public void ClearLog()
        {
            State.Delete();
        }

        #endregion

        private _ITextBoxAppend _State;
        public _ITextBoxAppend State
        {
            get { return _State; }
            set { if (_State != value) { _State = value; RaisePropertyChanged(""); } }
        }

    }


    #region 用于MVVM模型下TextBox控件的Append Text实现

    public class MvvmTextBox
    {
        public static readonly DependencyProperty BufferProperty =
            DependencyProperty.RegisterAttached("Buffer", typeof(_ITextBoxAppend), typeof(MvvmTextBox), new UIPropertyMetadata(null, PropertyChangedCallback));
        private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs depPropChangedEvArgs)
        {
            var textBox = (TextBox)dependencyObject;
            var textBuffer = (_ITextBoxAppend)depPropChangedEvArgs.NewValue;

            var detectChanges = true;

            textBox.Text = textBuffer.GetCurrentValue();
            textBuffer.BufferAppendedHandler += (sender, appendedText) =>
            {
                detectChanges = false;
                textBox.AppendText(appendedText);
                detectChanges = true;
            };

            textBuffer.BufferAppendedHandler_v1 += (sender, appendedText) =>
            {
                detectChanges = false;
                // 将 CaretIndex 设置为 0，以确保在文本框的开头插入
                textBox.CaretIndex = 0;
                // 将文本插入到 CaretIndex（即第 0 个字符处）
                textBox.SelectedText = appendedText;
                detectChanges = true;
            };

            textBuffer.BufferClearingHandler += (sender, clearingText) =>
            {
                detectChanges = false;
                textBox.Clear();
                detectChanges = true;
            };

            textBox.TextChanged += (sender, args) =>
            {
                if (!detectChanges)
                    return;
                foreach (var change in args.Changes)
                {
                    if (change.AddedLength > 0)
                    {
                        var addedContent = textBox.Text.Substring(
                            change.Offset, change.AddedLength);
                        textBuffer.Append(addedContent, change.Offset);
                    }
                    else
                    {
                        textBuffer.Delete(change.Offset, change.RemovedLength);
                    }
                }
                Debug.WriteLine(textBuffer.GetCurrentValue());
            };
        }

        public static void SetBuffer(UIElement element, bool value)
        {
            element.SetValue(BufferProperty, value);
        }
        public static _ITextBoxAppend GetBuffer(UIElement element)
        {
            return (_ITextBoxAppend)element.GetValue(BufferProperty);
        }
    }

    #region 接口定义
    public interface _ITextBoxAppend
    {

        void Delete();

        void Delete(int startIndex, int length);

        void Append(string value);

        void Append(string value, int index);

        string GetCurrentValue();

        event EventHandler<string> BufferAppendedHandler;

        event EventHandler<string> BufferAppendedHandler_v1;

        event EventHandler<string> BufferClearingHandler;
    }
    #endregion

    #region 接口实现

    class IClassTextBoxAppend : _ITextBoxAppend
    {
        private readonly StringBuilder _buffer = new StringBuilder();

        public void Delete()
        {
            _buffer.Clear();

            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                BufferClearingHandler(this, " ");
            }));
        }

        public void Delete(int startIndex, int length)
        {
            _buffer.Remove(startIndex, length);
        }

        public void Append(string value)
        {
            _buffer.Append(value);
            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                BufferAppendedHandler(this, value);
            }));
        }

        public void Append(string value, int index)
        {
            //if (index == _buffer.Length)
            //{
            //    _buffer.Append(value);
            //}
            //else
            //{
            //    _buffer.Insert(index, value);
            //}
            _buffer.Append(value);

            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                BufferAppendedHandler_v1(this, value);
            }));
        }

        public string GetCurrentValue()
        {
            return _buffer.ToString();
        }

        public event EventHandler<string> BufferAppendedHandler;

        public event EventHandler<string> BufferAppendedHandler_v1;

        public event EventHandler<string> BufferClearingHandler;
    }
    #endregion

    #endregion

}
